/**
 * 知识图谱节点类
 */
class KnowledgeNode {
    constructor(config, id, nodeType,data = {}, parent = null) {
        this.config = config;
        this.id = id;
        this.data = data;
        this.parent = parent;
        this.properties = this._buildProperties();
        this.children = [];
        this.nodeType = nodeType;
    }

    _buildProperties() {
        // 解析节点名称
        let nodeName;
        if (this.config.nodeName.startsWith('return ')) {
            const path = this.config.nodeName.replace('return ', '').split('.');
            nodeName = path.reduce((obj, key) => obj?.[key], this.data) || this.id;
        } else {
            nodeName = this.config.nodeName;
        }

        // 构建基础属性
        const properties = {
            name: nodeName,
            ...(typeof this.data === 'object' ? this.data : { value: this.data })
        };

        // 处理字段别名
        if (this.config.fieldAliasNames) {
            this.config.fieldAliasNames.forEach(alias => {
                const path = alias.fieldName;
                const aliasName = alias.aliasName;
                if (path.startsWith('return ')) {
                    const fieldPath = path.replace('return ', '').split('.');
                    const value = fieldPath.reduce((obj, key) => obj?.[key], this.data);
                    if (value !== undefined) {
                        properties[aliasName] = value;
                    }
                }
            });
        }

        return properties;
    }

    toNeo4jNode() {
        return {
            id: this.id,
            labels: [this.config.nodeName],
            properties: this.properties
        };
    }
}

/**
 * 知识图谱关系类
 */
class KnowledgeRelationship {
    constructor(type, source, target, properties = {}) {
        this.id = `${source}-${target}-${Date.now()}`;
        this.type = type;
        this.source = source;
        this.target = target;
        this.properties = properties;
    }

    toNeo4jRelationship() {
        return {
            id: this.id,
            type: this.type,
            startNode: this.source,
            endNode: this.target,
            properties: this.properties
        };
    }
}

/**
 * 知识图谱生成器
 */
class KnowledgeGraphGenerator {
    constructor(config) {
        this.config = config;
        this.nodeMap = new Map();
        this.relationships = [];
        this.mockData = this._initMockData();
    }

    _initMockData() {
        return {
            "http://urlPath/1": {
                content: [
                    { name: "阳光新城", kev2: "SG-2023-001" },
                    { name: "未来科技园", kev2: "SG-2023-002" }
                ]
            },
            "http://urlPath/2?key=阳光新城": {
                content: [
                    { name: "1号楼", jzbm: "BLD-001", xx: "A1" },
                    { name: "2号楼", jzbm: "BLD-002", xx: "A2" }
                ]
            },
            "http://urlPath/3?key1=1号楼": {
                content: {
                    name: "建设工程规划许可证-2023-001",
                    approvalCode: "AP-2023-001"
                }
            },
            "http://urlPath/4?key1=阳光新城&&code=AP-2023-001": {
                content: {
                    name: "审批通过",
                    date: "2023-05-15"
                }
            },
            "http://urlPath/5?key1=阳光新城": {
                content: [
                    { name: "单元A", units: ["101", "102"] },
                    { name: "单元B", units: ["201", "202"] }
                ]
            },
            "http://urlPath/6?key1=阳光新城&&key2=BLD-001": {
                content: [
                    { name: "F1", rooms: ["F1-101", "F1-102"] },
                    { name: "F2", rooms: ["F2-201", "F2-202"] }
                ]
            },
            "http://urlPath/7?key1=阳光新城&&key2=BLD-001": {
                content: [
                    { name: "F1-101", area: "45.6" },
                    { name: "F1-102", area: "52.3" }
                ]
            }
        };
    }

    generate() {
        // 初始化根节点
        const rootConfig = this.config.find(item => item.nodeId === "node1");
        const rootNode = new KnowledgeNode(rootConfig, "node1", "node1");
        this.nodeMap.set("node1", rootNode);

        // 分层生成图谱
        const layers = [];
        let currentLevel = ["node1"];
        let level = 1;

        while (currentLevel.length > 0) {
            const nextLevel = [];
            const layerResults = {
                nodes: [],
                relationships: []
            };

            for (const parentId of currentLevel) {
                const parentNode = this.nodeMap.get(parentId);
                if (!parentNode) continue;

                // 处理所有子节点配置
                const childrenConfigs = this.config.filter(item => item.parentNode === parentId.split('-')[0]);
                for (const childConfig of childrenConfigs) {
                    const children = this._processChildConfig(childConfig, parentNode);

                    for (const child of children) {
                        // 添加到节点映射
                        this.nodeMap.set(child.id, child);
                        parentNode.children.push(child);

                        // 创建关系
                        const relationship = new KnowledgeRelationship(
                            childConfig.relationName,
                            parentId,
                            child.id
                        );
                        this.relationships.push(relationship);

                        // 添加到当前层结果
                        layerResults.nodes.push(child.toNeo4jNode());
                        layerResults.relationships.push(relationship.toNeo4jRelationship());

                        // 记录下一层要处理的节点
                        nextLevel.push(child.id);
                    }
                }
            }

            // 保存当前层结果
            if (layerResults.nodes.length > 0 || layerResults.relationships.length > 0) {
                layers.push({
                    level: level++,
                    parentLevel: currentLevel,
                    results: [{
                        columns: this._getColumnsForLayer(layerResults),
                        data: [{
                            graph: {
                                nodes: layerResults.nodes,
                                relationships: layerResults.relationships
                            }
                        }]
                    }]
                });
            }

            // 准备处理下一层
            currentLevel = nextLevel;
        }

        return layers;
    }

    _processChildConfig(childConfig, parentNode) {
        const children = [];

        // 构建请求URL
        const url = this._buildUrl(childConfig.nodesFrom, parentNode);

        // 获取模拟数据
        const response = this.mockData[url] || { content: [] };
        const items = childConfig.nodeArray
            ? (Array.isArray(response.content) ? response.content : [response.content])
            : [response.content];

        // 创建子节点
        items.forEach((item, index) => {
            if (!item) return;

            const nodeId = `${childConfig.nodeId}-${index + 1}`;

            // 避免重复创建节点
            if (!this.nodeMap.has(nodeId)) {
                const childNode = new KnowledgeNode(childConfig, nodeId, childConfig.nodeId,item, parentNode);
                children.push(childNode);
            }
        });

        return children;
    }

    _buildUrl(urlTemplate, parentNode) {
        
        const matches = urlTemplate.match(/\{node\d+\.[a-zA-Z]+\}/g) || [];

        let url = urlTemplate;
        for (const match of matches) {
            const [nodeId, field] = match.slice(1, -1).split('.');

            // 从父节点链中查找属性
            let currentNode = parentNode;
            while (currentNode) {
                if (currentNode.nodeType === nodeId && currentNode.properties[field]) {
                    url = url.replace(match, currentNode.properties[field]);
                    break;
                }
                currentNode = currentNode.parent;
            }
        }
        console.log("_buildUrl", urlTemplate, parentNode,url);

        return url;
    }

    _getColumnsForLayer(layerResults) {
        const columns = new Set();

        // 添加节点类型
        layerResults.nodes.forEach(node => {
            columns.add(node.labels[0]);
        });

        // 添加关系类型
        layerResults.relationships.forEach(rel => {
            columns.add(rel.type);
        });

        return Array.from(columns);
    }
}

// 使用示例
const config = [
    {
        "nodeId": "node1",
        "nodeName": "项目"
    },
    {
        "nodeId": "node2",
        "parentNode": "node1",
        "relationName": "项目",
        "nodesFrom": "http://urlPath/1",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "return result.content",
        "nodeName": "return name",
        "fieldAliasNames": [
            {
                "fieldName": "return result.content.kev2",
                "aliasName": "cnName1"
            }
        ]
    },
    {
        "nodeId": "node3",
        "parentNode": "node2",
        "relationName": "建筑",
        "nodesFrom": "http://urlPath/2?key={node2.name}",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "return result.content",
        "nodeName": "return name"
    },
    {
        "nodeId": "node8",
        "parentNode": "node2",
        "relationName": "规划许可",
        "nodesFrom": "http://urlPath/3?key1={node3.name}",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "return result.content",
        "nodeName": "return result.content.name"
    },
    {
        "nodeId": "node4",
        "parentNode": "node2",
        "relationName": "审批结论",
        "nodesFrom": "http://urlPath/4?key1={node2.name}&&code={node8.approvalCode}",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "",
        "nodeName": "return result.content.name"
    },
    {
        "nodeId": "node5",
        "parentNode": "node3",
        "relationName": "单元",
        "nodesFrom": "http://urlPath/5?key1={node2.name}",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "return result.content",
        "nodeName": "return name"
    },
    {
        "nodeId": "node6",
        "parentNode": "node5",
        "relationName": "楼层",
        "nodesFrom": "http://urlPath/6?key1={node2.name}&&key2={node3.jzbm}",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "return result.content",
        "nodeName": "return name"
    },
    {
        "nodeId": "node7",
        "parentNode": "node6",
        "parentClickMenu": "加载房间",
        "relationName": "房间",
        "nodesFrom": "http://urlPath/7?key1={node2.name}&&key2={node3.jzbm}",
        "token": "AgCIM DataStore/NONE",
        "nodeArray": "return result.content",
        "nodeName": "return name"
    }
];

// 生成知识图谱
const generator = new KnowledgeGraphGenerator(config);
const layeredData = generator.generate();

// 打印结果
layeredData.forEach((layer, index) => {
    console.log(`\n=== 第 ${index + 1} 层 ===`);
    console.log(JSON.stringify(layer, null, 2));
});